/**
 * Copyright 2009 University of  Washington
 * This code is released under the GPL version 3 - with a copy of the license included
 * @author Maya Hao Li
 *
 */
package seedpod.webapp.view.htmlwidget;

import java.util.Vector;

public class SelectInput extends GenericHtmlWidget {
	private Vector<String> _options= new Vector<String>();
	private int _listSize = 1;
	private int _selectedIndex = 0;
	private boolean _multiple = false;

	public SelectInput(String widgetID) {
		super(widgetID);
	}

	public SelectInput(String widgetID, String value, String[] options) {
		this( widgetID, options );
		setSelectedValue( value );
	}

	public SelectInput(String widgetID, String[] options) {

		super( widgetID );
		if ( options != null ) {
			for ( int i = 0; i < options.length; i++ )
				_options.add( options[i] );
		}
	}

	public SelectInput(String widgetID, Vector<String> options) {
		super( widgetID );
		_options = options;
	}

	public void setAllowsMultiple( boolean m ) {
		_multiple = m;
	}

	public boolean allowsMultiple() {
		return _multiple;
	}

	public void setSelectedIndex( int select ) {
		_selectedIndex = select;
	}

	public void setSelectedValue( String val ) {
		for ( int i = 0; i < _options.size(); i++ ) {
			if ( _options.elementAt( i ).equals( val ) ) {
				setSelectedIndex( i );
				return;
			}
		}
	}

	public void addOption( String op ) {
		_options.add( op );
	}

	public void setSize( int size ) {
		_listSize = size;
	}

	public String render() {
		StringBuffer html = new StringBuffer();
		html.append( "<select " );
		html.append( ATT( "id", _widgetID ) );
		html.append( ATT( "name", _widgetID ) );
		html.append( ATT( "size", _listSize ) );
		if ( _multiple )
			html.append( " multiple " );
		html.append( ">" );

		if ( _options != null ) {
			for ( int i = 0; i < _options.size(); i++ ) {
				html.append( "<option " + ATT( "value", _options.elementAt( i ) ) );
				if ( i == _selectedIndex )
					html.append( "selected" );
				html.append( ">" );
				html.append( _options.elementAt( i ) );
				html.append( "</option>" );
			}
		}

		html.append( "</select>" );
		return html.toString();
	}

}